package com.sunway.android.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.Bitmap;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;

import com.sunway.android.R;
import com.sunway.android.beans.ImagesInformationsBean;
import com.sunway.android.utils.AsyncImageLoader;
import com.sunway.android.utils.DisplayUtil;

public class GridViewImageAdapter extends BaseAdapter {
	private Context context;
	private AsyncImageLoader asyncImageLoader = null;
	private List<ImagesInformationsBean> imagesInformationsBeanList = null;

	public GridViewImageAdapter(Context context) {
		this.context = context;
	}

	@Override
	public int getCount() {
		if (imagesInformationsBeanList != null) {
			return imagesInformationsBeanList.size();
		}
		return 0;
	}

	@Override
	public Object getItem(int position) {
		if (imagesInformationsBeanList != null) {
			return imagesInformationsBeanList.get(position);
		}
		return null;
	}

	@Override
	public long getItemId(int position) {
		if (imagesInformationsBeanList != null
				&& position - 1 <= imagesInformationsBeanList.size()) {
			return position;
		}
		return 0;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView imageView;
		if (convertView == null) {
			imageView = new ImageView(context);
			imageView.setLayoutParams(new GridView.LayoutParams(100, 100));
			imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
			imageView.setPadding(8, 8, 8, 8);
		} else {
			imageView = (ImageView) convertView;
		}
		if (asyncImageLoader == null || imagesInformationsBeanList == null) {
			imageView.setImageBitmap(DisplayUtil
					.decodeSampledBitmapFromResource(context.getResources(),
							R.drawable.image_loading, 90, 90));
		} else {
			ImagesInformationsBean imagesInformationsBean = imagesInformationsBeanList
					.get(position);

			ImageCallback imageCallback = new ImageCallback();
			imageCallback.setImageView(imageView);

			Bitmap bitmap = asyncImageLoader.loadDrawable(
					imagesInformationsBean.getUrl(), imageCallback);

			if (bitmap == null) {
				imageView.setImageBitmap(DisplayUtil
						.decodeSampledBitmapFromResource(
								context.getResources(),
								R.drawable.image_loading, 90, 90));
			}
		}

		return imageView;
	}

	public void setAsyncImageLoaderAndLFDEntityList(
			List<ImagesInformationsBean> imagesInformationsBeanList,
			AsyncImageLoader asyncImageLoader) {
		this.asyncImageLoader = asyncImageLoader;
		this.imagesInformationsBeanList = imagesInformationsBeanList;
	}

	private class ImageCallback implements AsyncImageLoader.ImageCallback {
		private ImageView imageView;

		@Override
		public void imageLoaded(Bitmap bitmap) {
			imageView.setImageBitmap(bitmap);
		}

		public void setImageView(ImageView imageView) {
			this.imageView = imageView;
		}

	}

}
